package com.web.model;

import com.jfinal.plugin.activerecord.Model;
import com.web.util.Properties;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * Created by reeves on 2015/7/4.
 * PageTitleImage类属于Model层，对应数据库表page_titleimage
 */
/*
page_titleimage表
+----------------+--------------+------+-----+---------------+--------+
| Field          | Type         | Null | Key |    Default    | Extra  |
+----------------+--------------+------+-----+---------------+--------+
| imageId        | varchar(15)  | NO   | PRI |  000000       |        |
| imageSrc       | varchar(255) | YES  |     |  Empty String |        |
| imageSrc2      | varchar(255) | YES  |     |  Empty String |        |
+----------------+--------------+------+-----+---------------+--------+
*/
public class PageTitleImage extends Model<PageTitleImage> {
    private static final Logger LOGGER = Logger.getLogger(PageTitleImage.class);
    public static final PageTitleImage pageTitleImageDao = new PageTitleImage();


    public String getLocalPathById(String imageid) {
        String sql = "SELECT * FROM page_titleimage WHERE imageId = ?";
        PageTitleImage pageTitleImage = PageTitleImage.pageTitleImageDao.findFirst(sql, imageid);
        String Source = pageTitleImage.getStr("imageSource");
        String LocalPath = Properties.ImgSaveDir_Windows + Source;
        return LocalPath;
    }

    // 获取到所有标题图片对象
    public List<PageTitleImage> getAllTitleImage() {
        return PageTitleImage.pageTitleImageDao.find("SELECT imageId,imageSource,imageSrc,imageSrc2,pageImageSrc FROM page_titleimage");
    }

    // 更新数据库对象
    public boolean updateTitleImage(List<PageTitleImage> pageTitleImageList) {

        try {
            for (PageTitleImage pageTitleImage : pageTitleImageList) {
                pageTitleImageDao.findById(pageTitleImage.getStr("imageId")).set("imageSrc", pageTitleImage.getStr("imageSrc")).update();

                if (pageTitleImageDao.findById(pageTitleImage.getStr("imageId")).get("imageSrc2") != null) {
                    pageTitleImageDao.findById(pageTitleImage.getStr("imageId")).set("imageSrc2", pageTitleImage.getStr("imageSrc2")).update();
                }
            }
        } catch (Exception exception) {
            LOGGER.error("更新数据库page_titleImage错误", exception);
            return false;
        }
        return true;

    }
}
